package com.longrise.android.byjk.plugins.vip.integralexchange;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.common.base.BaseFragment;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.MineRefreshEvent;
import com.longrise.android.byjk.event.MyIntegralEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BBswipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by callxkj on 2017/7/22.
 * 积分兑换中的 展业秀勋章
 */

public class IExchangezyxxzFragment extends BaseFragment implements View.OnClickListener,
        SwipeRefreshLayout.OnRefreshListener, OnIntegralExchangeRcvItemClickListener {


    private static final String TAG = "IExchangezyxxzFragment";
    private BBswipeRefreshLayout mBbsrl;
    private RecyclerView mRcv;
    private IExchangezyxxzAdapter mAdapter;
    private RelativeLayout mRl1;
    private TextView mTv1;
    private ImageView mIv1;
    private boolean mIsVisibleToUser;
    private boolean mViewCreated;

    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_iexchangezyxxz;
    }

    @Override
    public void initView() {
        mViewCreated = true;
        mBbsrl = (BBswipeRefreshLayout) mRootView.findViewById(R.id.iexchagezyxxz_srl);
        mRcv = (RecyclerView) mRootView.findViewById(R.id.iexchagezyxxz_rcv);
        mRl1 = (RelativeLayout) mRootView.findViewById(R.id.iexchagezyxxz_rl1);
        mTv1 = (TextView) mRootView.findViewById(R.id.iexchagezyxxz_tv1);
        mIv1 = (ImageView) mRootView.findViewById(R.id.iexchagezyxxz_iv1);
        initRcv();
        if (mIsVisibleToUser) {
            initData();
        }
        initEvent();
        addScreenName("勋章兑换");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) { //页面可见的时候isVisibleToUser 为true
        super.setUserVisibleHint(isVisibleToUser);
        this.mIsVisibleToUser = isVisibleToUser;
        if (mIsVisibleToUser && mViewCreated) {
            initData();
            mViewCreated = false; //使页面切换过来后 不自动加载
        }
    }

    private void initRcv() {
        View headView = View.inflate(mContext, R.layout.item_rcv_integralexchange_head, null);
        mAdapter = new IExchangezyxxzAdapter("勋章兑换");
        mAdapter.addHeaderView(headView);
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2, GridLayoutManager.VERTICAL, false);
        mRcv.setLayoutManager(layoutManager);
        mRcv.setAdapter(mAdapter);
        mAdapter.setOnRcvItemClickListener(this);
    }

    private void initData() {
        getData(true);
    }

    private void initEvent() {
        mBbsrl.setOnRefreshListener(this);
        mIv1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iexchagezyxxz_iv1:
                mRl1.setVisibility(View.GONE);
                Control.setIsShowzxyxzTips(false);
                addGoogleEvent("勋章兑换提示","关闭",null);
                break;
        }
    }

    /**
     * 重新获取数据并展示
     * @param flag 是否用swipeRefreshLayout的刷新
     */
    private void getData(boolean flag) {
        mBbsrl.setRefreshing(flag);
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_sMedalInfobygoodstype", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int value = (Integer) bean.get("resultstate");
                            if (value == 1) {
                                EntityBean[] results = bean.getBeans("result");
                                parseResult(results);
                                initBtmTips();
                                MyMedalRankHelper.reloadRank((Activity) mContext,false);
                            } else {
                                showToast(resultdesc);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        refreshComplete();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }

    private void parseResult(EntityBean[] beans) {
        EntityBean bean = beans[0];
        EntityBean[] goodsinfos = bean.getBeans("goodsinfo");
        String goodstype = bean.getString("goodstype");
        mAdapter.setDatas(goodsinfos, goodstype);
    }

    /**
     * 初始化底部提示栏
     */
    private void initBtmTips() {
        boolean isShowzxyxzTips = Control.getIsShowzxyxzTips();
        if (isShowzxyxzTips) {
            mRl1.setVisibility(View.VISIBLE);
            //------ 初始化iv ---------------------------------------
            String s1 = "<font color = #FFFFFF>勋章有效期均为</font>";
            String s2 = "<font color = #FFA200>10</font>";
            String s3 = "<font color = #FFFFFF>天，最多展示</font>";
            String s4 = "<font color = #FFA200>5</font>";
            String s5 = "<font color = #FFFFFF>个</font>";
            String s6 = s1 + s2 + s3 + s4 + s5;
            mTv1.setText(Html.fromHtml(s6));
        }
    }


    /**
     * 1.3.6改版 积分兑换之前先判断积分是否充足
     * 检查积分是否充足
     */
    private void checkIsEnoughIntegral(final String goodsid, final String goodstype, final String needscores) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("goodsid", goodsid);
        bean.set("goodstype", goodstype);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        showLoadingDialog();
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_isEnoughCostgoods", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int resultstate = (Integer) bean.get("resultstate");
                            if (resultstate == 1) { //积分充足
                                IntegralExchangeDialogHelper.toShowIntegralExchangexzDialog((BaseActivity) getActivity(),
                                        goodsid, goodstype, needscores,
                                        new IntegralExchangeDialogHelper.ToIntegralExchangeListener() {
                                            @Override
                                            public void toIntegralExchange(String goodsid, String goodstype) {
                                                togetIntegralExchange(goodsid, goodstype);
                                            }
                                        });
                            } else if (resultstate == 2) { //积分不足
                                IntegralExchangeDialogHelper.showIntegralnotenoughtDialog((BaseActivity) getActivity());
                            } else {
                                showToast(resultdesc);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }

    /**
     * 积分勋章兑换
     */
    private void togetIntegralExchange(String goodsid, String goodstype) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("goodsid", goodsid);
        bean.set("goodstype", goodstype);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        showLoadingDialog();
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_iScoresCostRecord", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int resultstate = (Integer) bean.get("resultstate");
                            if (resultstate == 1) { //积分兑换成功
                                showToast(resultdesc);
                                getData(false);
                                EventBus.getDefault().post(new MyIntegralEvent(true));
                                MineRefreshEvent mineRefreshEvent = new MineRefreshEvent();
                                mineRefreshEvent.setBBye(true);
                                EventBus.getDefault().post(mineRefreshEvent); //我的页面保宝余额与我的积分是同一个接口

                            } else if (resultstate == 2) { //积分不足
                                IntegralExchangeDialogHelper.showIntegralnotenoughtDialog((BaseActivity) getActivity());
                            } else {
                                showToast(resultdesc);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }

    /**
     * 使用或者取消勋章
     */
    private void toUseMedal(String medalid, String medalstate) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("medalid", medalid);
        bean.set("medalstate", medalstate);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_vip_uVIPstateByMedalid", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            String resultdesc = bean.getString("resultdesc");
                            int resultstate = (Integer) bean.get("resultstate");
                            if (resultstate == 1) {
                                getData(false);
                            }
                            showToast(resultdesc);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });
    }


    /**
     * 显示网络加载dialog
     */
    public void showLoadingDialog() {
        DZZWTools.showWaitDialog(mContext);
    }

    /**
     * 隐藏网络加载dialog
     */
    public void dismissLoadingDialog() {
        DZZWTools.dismissDialog(null);
    }

    /**
     * rcv 下拉刷新完成
     */
    private void refreshComplete() {
        mBbsrl.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        getData(true);
    }


    /**
     * 点击使用积分兑换
     */
    @Override
    public void onClick(int type, String lockstate, String goodsid, String goodstype,
                        String needscores, String imageUrl, String detailpicurl, int position) {
        if ("0".equals(lockstate) || "3".equals(lockstate)) {  //商品到期 也要重新购买
            checkIsEnoughIntegral(goodsid, goodstype, needscores);
        } else {  //1:已解锁 在使用  0：未解锁 2:已解锁 未使用 3.已解锁 商品到期
            toUseMedal(goodsid, lockstate);
        }
    }




    private void addScreenName(String name) {
        Tracker_Google.getInstance().addGoogleScreenName(name);
    }

    private void addGoogleEvent(String par1, String par2, String par3) {
        Tracker_Google.getInstance().addEvent(par1, par2, par3);
    }

}
